<?php

class Admin_CategoryController extends Zend_Controller_Action {

    /**
     * @var Nosql_Model_Category
     * 
     * 
     */
    private $categoryModel = null;

    public function init() {
        $this->categoryModel = new Nosql_Model_Mysql_Category;
        $this->view->sidebarMenu = 'category';
        $this->view->userObj = Zend_Auth::getInstance()->getIdentity();
    }

    public function indexAction() {
        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }

        $categories = $this->categoryModel->listCategories($page);
        $this->view->categories = $categories['items'];
        if (count($this->view->categories) == 0) {
            $this->view->attention = array('No se encontraron usuarios');
        } else {
            $this->view->paginator = $categories['paginator'];
            $this->view->urlPagination = '/admin/category/index/';
        }
    }

    public function addAction() {
        $form = new Admin_Form_Category();
        $form = $form->addCategory();
        $errors = array();

        //Validate the form
        $request = $this->getRequest();
        if ($request->isPost()) {
            //valiate if theh form is valid
            if ($form->isValid($request->getPost())) {

                $formValues = $form->getValues();

                //validate if the category doesn't exists
                if ($this->categoryModel->categoryExists($formValues['category']['name'])) {
                    $errors[] = 'El nombre de la categoria ya existe, seleccione otro';
                }

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['name'] = $formValues['category']['name'];
                    if (isset($formValues['category']['parentId']) && $formValues['category']['parentId'] > -1) {
                        $data['parentId'] = $formValues['category']['parentId'];
                    }

                    $response = $this->categoryModel->createCategory($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Categoría creado");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        $this->view->form = $form;
    }

    public function deleteAction() {
        $success = array();
        $errors = array();
        $id = $this->getRequest()->getParam('category');
        if ($id == null || !is_numeric($id)) {
            $errors = array("No selecciono ninguna categoría");
        } else {
            $response = $this->categoryModel->deleteCategoryById($id);
            if ($response['status'] > 0) {

                $success[] = $response['message'];
            } else {
                $errors[] = $response['message'];
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }

        $this->_forward('index');
        return;
    }

    public function editAction() {
        $form = new Admin_Form_Category();
        $errors = array();
        $continue = true;

        //Validate the form
        $request = $this->getRequest();

        //get the User Object
        $id = $request->getParam('category');
        if ($id == null || !is_numeric($id)) {
            $continue = false;
            $errors[] = "No selecciono ninguna categoría";
        }

        $category = null;
        if ($continue) {
            $category = $this->categoryModel->getCategoryById($id);
            if (!$category) {
                $continue = false;
                $errors[] = 'Hubo un error al obtener la categoría';
            } else {
                $form = $form->editCategory($category['categoryid']);
            }
        }

        if ($continue && $request->isPost()) {
            //valiate if theh form is valid
            if ($form->isValid($request->getPost())) {

                $formValues = $form->getValues();

                // if there are no errors then I can create the user
                if (count($errors) == 0) {

                    $data['name'] = $formValues['category']['name'];
                    $data['parentId'] = $formValues['category']['parentId'];
                    $data['categoryid'] = $category['categoryid'];
                    if (!isset($formValues['category']['parentId']) || $data['parentId'] == -1) {
                        unset($data['parentId']);
                    }

                    $response = $this->categoryModel->updateCategory($data);
                    if ($response['status'] > -1) {
                        $this->view->success = array("Categoría actualizada exitosamente");
                        $this->_forward('index');
                        return;
                    } else {
                        $errors[] = $response['message'];
                    }
                }
            }
        }

        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }

        if ($continue) {
            //Populate the Form
            $data['name'] = $category['name'];
            $data['parentid'] = $category['parentid'];

            $form->populate($data);
            $this->view->form = $form;
        }

        if (!$continue) {
            $this->_forward('index');
        }
    }

    public function searchAction() {
        $form = new Admin_Form_Category();
        $errors = array();
        $success = array();
        $information = array();
        $continue = true;

        $page = $this->_getParam('page');
        $page = (isset($page)) ? $page : 1;

        if (!Nosql_Util_Validator::validateInt($page)) {
            throw new Exception('Valor invalido en los parametros');
        }


        $form = $form->searchCategory();
        $request = $this->getRequest();
        if ($continue && $form->isValid($request->getParams())) {
            $formValues = $form->getValues();
            $query = $formValues['category']['q'];
            $field = $formValues['category']['field'];

            // NOW PREPARE THE VALUES TO DO THE SEARCH
            $useLiteral = false;
            switch ($field) {
                case 1:
                    $field = 'name';
                    $useLiteral = true;
                    break;
                case 2:
                    $field = 'categoryid';
                    break;
                default:
                    $field = '';
                    break;
            }

            if (strlen($query) > 0) {
                $categories = $this->categoryModel->searchCategoryByField($query, $field, $useLiteral, $page);
                if ($categories['items']) {
                    $this->view->categories = $categories['items'];
                    $this->view->paginator = $categories['paginator'];
                    $this->view->urlPagination = '/admin/category/search/q/' . $query . '/field/' . $formValues['category']['field'] . '/';
                } else {
                    $information[] = 'Categorías no encontradas';
                }
            } else {
                $errors[] = 'Campo seleccionado es invalido';
            }
        }


        if (count($errors) > 0) {
            $this->view->errors = $errors;
        }
        if (count($success) > 0) {
            $this->view->success = $success;
        }
        if (count($information) > 0) {
            $this->view->information = $information;
        }
        $this->view->form = $form;
    }

}

